<template>
  <div class="background">
    <el-card class="login">
      <template #header>
        <div class="card-header">
          <h3>网上书店后台系统</h3>
        </div>
      </template>
      <el-form
        label-position="top"
        label-width
        :model="loginModel"
        class="login-form"
        @submit.prevent
      >
        <el-form-item label="用户名">
          <el-input v-model="loginModel.username"></el-input>
        </el-form-item>
        <el-form-item label="密码">
          <el-input v-model="loginModel.password" show-password></el-input>
        </el-form-item>
        <el-form-item label="验证码">
          <div class="code">
            <el-input
              class="m_input"
              v-model="loginModel.captcha.text"
            ></el-input>
            <span @click="getCode" v-html="loginModel.captcha.data"></span>
          </div>
        </el-form-item>
        <el-form-item>
          <el-button @click="login" native-type="submit" type="primary"
            >登录</el-button
          >
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script lang="ts" setup>
import {
  ElMessage,
  ElCard,
  ElButton,
  ElForm,
  ElFormItem,
  ElInput,
} from "element-plus";
import { ref } from "vue";

import { http } from "../http";
import { Login } from "../interface/login.interface";
import { useRouter } from "vue-router";

const router = useRouter();
const loginModel = ref<Login>({
  username: "",
  password: "",
  captcha: {
    id: "",
    text: "",
    data: "",
  },
});

async function getCode() {
  loginModel.value.captcha = (await http.get("/auth/captcha")).data;
}

getCode();

async function login() {
  try {
    const data = (await http.post("/auth/login", loginModel.value)).data;
    localStorage.adminToken = data.token;
    router.push("/");
    ElMessage.success("登录成功");
  } catch (e) {
    ElMessage.error("登录失败");
    getCode();
  }
}
</script>

<style lang="scss">
.background {
  height: 100vh;
  width: 100vw;
  display: flex;
  align-items: center;
  justify-content: center;
  background: url("../assets/images/wallroom-1920x1080-bg-8841766.jpg") center
    no-repeat;

  .login {
    max-width: 960px;

    h3 {
      margin: 0;
    }

    .login-form {
      padding: 0 2em;

      .code {
        width: 100%;
        display: flex;
        align-items: center;
        justify-content: space-between;

        .m_input {
          flex: 3;
        }

        span {
          cursor: pointer;
          flex: 1;
        }
      }
    }
  }
}
</style>
